<!--
  @author:  long
  @date:    2023/4/7
  @file:    考评评分
  @require:
-->
<template>
  <div class="scoreTable">
    <FixedOperation>
      <div class="flex items-center justify-between">
        <span style="font-size: 16px; font-weight: 600">绩效考评</span>
        <!-- 内容 -->
        <div class="text-right" v-if="props.type == 'self'">
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button type="danger" @click="handleBack('self')">返回</el-button>
        </div>
        <div class="text-right" v-if="props.type == 'other'">
          <el-button
            type="primary"
            :loading="loading"
            :disabled="loading"
            v-if="isActive > 0"
            @click="handleSwitchPerson('pre')"
            >上一人
          </el-button>
          <el-button
            type="primary"
            :loading="loading"
            :disabled="loading"
            @click="handleSwitchPerson('next')"
            v-if="isActive < userIds.length - 1"
            >下一人
          </el-button>
          <el-button type="success" @click="handleSave">保存</el-button>
          <el-button type="danger" @click="handleBack('list')"
            >返回列表
          </el-button>
        </div>
      </div>
    </FixedOperation>
    <div class="app-container">
      <el-row class="mb-2 text-sm text-15px flex items-center">
        <el-col :span="3" class="text-15px"
          >被考核人：
          <span class="text-15px" style="color: red">
            {{
              tableData.length > 0
                ? tableData[0].appraiseeName == null
                  ? '--'
                  : tableData[0].appraiseeName
                : '--'
            }}
          </span>
        </el-col>
        <el-col :span="3" class="text-15px"
          >所在部门：
          <span class="text-15px" style="color: red">
            {{
              tableData.length > 0
                ? tableData[0].appraiseeDeptName == null
                  ? '--'
                  : tableData[0].appraiseeDeptName
                : '--'
            }}
          </span>
        </el-col>
        <el-col :span="3" class="text-15px"
          >职务：
          <span class="text-15px" style="color: red">
            {{
              tableData.length > 0
                ? tableData[0].appraiseeDuties == null
                  ? '--'
                  : tableData[0].appraiseeDuties
                : '--'
            }}
          </span>
        </el-col>
        <el-col :span="4" class="text-15px"
          >岗位：
          <span class="text-15px" style="color: red">
            {{
              tableData.length > 0
                ? tableData[0].appraiseePost == null
                  ? '--'
                  : tableData[0].appraiseePost
                : '--'
            }}
          </span>
        </el-col>
        <el-col :span="8" class="text-15px"
          >绩效考评时间：
          <span class="text-15px" style="color: red">
            {{
              tableData.length > 0
                ? tableData[0].assessRemark == null
                  ? '--'
                  : tableData[0].assessRemark
                : '--'
            }}
          </span>
        </el-col>
        <el-col :span="3" class="text-right">
          <el-button type="primary" link @click="getPreScore"
            >上次评分
          </el-button>
        </el-col>
      </el-row>

      <el-table
        :data="tableData"
        border
        :span-method="spanMethod"
        :summary-method="getSummaries"
        show-summary
        :header-cell-style="{ textAlign: 'center' }"
        v-loading="loading"
      >
        <el-table-column
          type="index"
          label="序号"
          fixed="left"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          label="一级指标"
          fixed="left"
          prop="firstLevel"
          show-overflow-tooltip
          width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          label="二级指标"
          fixed="left"
          show-overflow-tooltip
          prop="secondLevel"
          width="100"
        ></el-table-column>
        <el-table-column
          label="指标说明及工作内容、工作要求等"
          width="220"
          fixed="left"
          prop="content"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="分值权重"
          fixed="left"
          width="80"
          prop="score"
          align="center"
        ></el-table-column>
        <!-- <el-table-column label="指标单位" width="100" prop="unit"> -->
        <!--          <template #default="scope">-->
        <!--            <dict-tag :options="indicator_unit" :value="scope.row.unit" />-->
        <!--          </template>-->
        <!-- </el-table-column> -->
        <el-table-column label="指标值" width="85" prop="targetValue">
          <template #default="scope">
            <div>
              {{ scope.row.targetValue + scope.row.unit }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="考核评分标准"
          show-overflow-tooltip
          prop="scoreStandard"
        ></el-table-column>

        <el-table-column
          label="计分方式"
          width="80"
          align="center"
          fixed="right"
          prop="scoreMethod"
        >
          <template #default="scope">
            <dict-tag
              :options="scoring_method"
              :value="scope.row.scoreMethod"
            />
            <!--      计算百分比        -->
            <div v-if="scope.row.scoreMethod == '2'">
              {{
                scope.row.scoreDescriptionSelf == '' ||
                scope.row.scoreDescriptionSelf == null
                  ? '——'
                  : Math.round(
                      ((scope.row.scoreDescriptionSelf * 1) /
                        scope.row.targetValue) *
                        10000
                    ) /
                      100 +
                    '%'
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="完成情况"
          v-if="props.type == 'self'"
          width="150"
          fixed="right"
          prop="scoreDescriptionSelf"
        >
          <template #header>
            <span style="font-weight: bold">完成情况</span>
          </template>
          <template #default="scope">
            <div class="flex items-center">
              <el-input
                v-if="scope.row.scoreMethod == '2'"
                v-model="scope.row.scoreDescriptionSelf"
                :type="scope.row.scoreMethod == '2' ? 'number' : 'text'"
                @input="
                  val => {
                    scoreDescriptionSelfInput(val, scope.row)
                  }
                "
                maxlength="500"
              >
              </el-input>
              <el-input
                v-else
                v-model="scope.row.scoreDescriptionSelf"
                maxlength="500"
                @focus="handleUploadFile(scope.row)"
              >
              </el-input>
              <i
                style="font-size: 18px"
                class="i-cil-paperclip ml-2"
                :class="
                  scope.row.fileNum * 1 > 0 ? 'text-blue-500' : 'text-slate-400'
                "
                @click="handleUploadFile(scope.row)"
              ></i>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="完成情况"
          v-if="props.type == 'other'"
          width="150"
          fixed="right"
          prop="assessDescription"
        >
          <template #header>
            <span style="font-weight: bold">完成情况</span>
          </template>
          <template #default="scope">
            <div class="flex items-center">
              <el-input
                v-if="scope.row.scoreMethod == '2'"
                v-model="scope.row.assessDescription"
                :type="scope.row.scoreMethod == '2' ? 'number' : 'text'"
                @input="
                  val => {
                    scoreDescriptionSelfInput(val, scope.row)
                  }
                "
                maxlength="500"
              >
              </el-input>
              <el-input
                v-else
                v-model="scope.row.assessDescription"
                maxlength="500"
                @focus="handleUploadFile(scope.row)"
              >
              </el-input>
              <i
                style="font-size: 18px"
                class="i-cil-paperclip ml-2"
                :class="
                  scope.row.fileNum * 1 > 0 ? 'text-blue-500' : 'text-slate-400'
                "
                @click="handleUploadFile(scope.row)"
              ></i>
            </div>
          </template>
        </el-table-column>
        <!--          自评得分-->
        <el-table-column
          v-if="props.type == 'other'"
          fixed="right"
          label="自评得分"
          align="center"
          width="80"
          prop="finalScoreSelf"
        >
        </el-table-column>
        <el-table-column label="评分" align="center" fixed="right" width="120">
          <template #header>
            <span style="color: red; font-weight: bold">评分</span>
          </template>
          <template #default="scope">
            <el-popover
              placement="left"
              :hide-after="0"
              :width="400"
              :offset="250"
              trigger="hover"
            >
              <template #reference>
                <el-input
                  v-model="scope.row.scoreSelf"
                  v-if="scope.row.scoreMethod == '1'"
                  @change="
                    val => {
                      scoreInputChange(scope.row, val)
                    }
                  "
                ></el-input>
                <!--      加分        -->
                <el-input
                  v-model="scope.row.scoreSelf"
                  type="number"
                  v-else-if="scope.row.scoreMethod == '3'"
                  :min="0"
                  :max="scope.row.score - scope.row.basicScore"
                  @change="
                    val => {
                      scoreInputChange(scope.row, val)
                    }
                  "
                >
                  <template #prepend><span> 加 </span></template>
                </el-input>
                <!--      减分        -->
                <el-input
                  v-model="scope.row.scoreSelf"
                  type="number"
                  :max="scope.row.score * 1"
                  v-else-if="scope.row.scoreMethod == '4'"
                  @change="
                    val => {
                      scoreInputChange(scope.row, val)
                    }
                  "
                >
                  <template #prepend>
                    <span style="color: red"> 扣</span>
                  </template>
                </el-input>
                <el-input-number
                  v-else
                  :min="
                    scope.row.scoreMethod == '1'
                      ? scope.row.score == '减分项' ||
                        scope.row.score == '加/减分项'
                        ? -9999
                        : 0
                      : 0
                  "
                  :max="
                    scope.row.scoreMethod == '3'
                      ? scope.row.score - scope.row.basicScore
                      : scope.row.scoreMethod == '1'
                      ? scope.row.scope == '加分项'
                        ? 9999
                        : scope.row.score * 1
                      : scope.row.score * 1
                  "
                  v-model="scope.row.scoreSelf"
                  :disabled="scope.row.scoreMethod == '2'"
                  @input="
                    val => {
                      handleGradeBlur(scope.row, val)
                    }
                  "
                  @change="
                    val => {
                      handleGradeInput(scope.row, val)
                    }
                  "
                ></el-input-number>
              </template>
              <div>
                <div style="font-weight: bold" class="mb-2">指标说明</div>
                <div class="mb-2 pl-2 text-xs">
                  {{ scope.row.content }}
                </div>
                <div style="font-weight: bold" class="mb-2">考核评分标准</div>
                <div class="mb-2 pl-2 text-xs">
                  {{ scope.row.scoreStandard }}
                </div>
                <div style="font-weight: bold" class="mb-2">分值权重</div>
                <div class="mb-2 pl-2 text-xs">
                  {{ scope.row.score }}
                </div>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <!--          自评得分-->
        <el-table-column
          v-if="props.type == 'self'"
          fixed="right"
          label="得分"
          align="center"
          width="60"
          prop="finalScoreSelf"
        >
          <template #header>
            <span style="color: red; font-weight: bold">得分</span>
          </template>
          <template #default="scope">
            <div style="color: rgb(243, 151, 12); font-weight: 600">
              {{ scope.row.finalScoreSelf }}
            </div>
          </template>
        </el-table-column>
        <!--          他评得分-->
        <el-table-column
          v-if="props.type == 'other'"
          fixed="right"
          label="得分"
          align="center"
          width="60"
          prop="finalAssessScore"
        >
          <template #header>
            <span style="color: red; font-weight: bold">得分</span>
          </template>
          <template #default="scope">
            <div style="color: rgb(243, 151, 12); font-weight: 600">
              {{ scope.row.finalAssessScore }}
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        v-model="dialogVisible"
        title="完成情况"
        width="55%"
        :before-close="handleFileDialogClose"
      >
        <el-form modal="fileForm" label-width="120">
          <div v-if="props.type == 'other'">
            <TitleName
              class="mb-5"
              title="自评"
              icon="i-carbon-bookmark-filled"
            ></TitleName>
            <div class="pl-10">
              <el-form-item label="完成情况：">
                <div>{{ fileForm.scoreDescriptionSelf }}</div>
              </el-form-item>
              <el-form-item label="附件:">
                <div class="text-14px" style="width: 100%">
                  <div v-for="item in selfFileList" :key="item.fileId">
                    <!--                <a :href="item.url">{{ item.origFileName }}</a>-->
                    <el-button type="primary" link @click="viewFile(item.url)"
                      >{{ item.origFileName }}
                    </el-button>
                  </div>
                </div>
              </el-form-item>
            </div>
            <el-divider />
          </div>
          <TitleName
            class="mb-5"
            :title="props.type == 'other' ? '他评' : '自评'"
            icon="i-carbon-bookmark-filled"
          ></TitleName>
          <div class="px-10">
            <el-form-item label="指标说明：">
              <div>
                {{ fileForm.content }}
              </div>
            </el-form-item>
            <el-form-item label="考核评分标准：">
              <div>
                {{ fileForm.scoreStandard }}
              </div>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="分值权重：">
                  <div>
                    {{ fileForm.score }}
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="计分方式：">
                  <div>
                    <dict-tag
                      :options="scoring_method"
                      :value="fileForm.scoreMethod"
                    />
                  </div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="完成情况：">
              <el-input
                v-if="props.type == 'self'"
                type="textarea"
                :rows="5"
                placeholder="请输入完成情况"
                v-model="fileForm.scoreDescriptionSelf"
              ></el-input>
              <el-input
                v-if="props.type == 'other'"
                type="textarea"
                :rows="5"
                placeholder="请输入完成情况"
                v-model="fileForm.assessDescription"
              ></el-input>
            </el-form-item>
            <el-form-item label="附件：">
              <el-upload
                class="upload-demo"
                action="#"
                :disabled="fileList && fileList.length >= 5"
                :before-upload="beforeAvatarUpload"
                :http-request="
                  params => {
                    handleFileChange(params)
                  }
                "
                accept=".xls,.xlsx,.rar, .zip, .doc, .docx, .pdf,.png,.jpg,.jpeg"
                :show-file-list="false"
              >
                <el-button type="primary" style="font-size: 14px" class="mr-5">
                  <el-icon>
                    <UploadFilled />
                  </el-icon>
                  上传附件
                </el-button>
                <div class="el-upload__tip">
                  <span>最多上传5个文件</span>
                </div>
              </el-upload>
              <div class="text-14px mt-10px" style="width: 100%">
                <div v-for="(item, index) in fileList" :key="item.fileId">
                  <!--                <a :href="item.url">{{ item.origFileName }}</a>-->
                  <el-button type="primary" link @click="viewFile(item.url)"
                    >{{ item.origFileName }}
                  </el-button>
                  <el-button text plain @click="delFileName(index, 'file')"
                    >删除
                  </el-button>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="评分：">
              <el-input
                v-model="fileForm.scoreSelf"
                v-if="fileForm.scoreMethod == '1'"
                @change="
                  val => {
                    scoreInputChange(fileForm, val)
                  }
                "
              ></el-input>
              <!--      加分        -->
              <el-input
                v-model="fileForm.scoreSelf"
                type="number"
                v-else-if="fileForm.scoreMethod == '3'"
                :min="0"
                :max="fileForm.score - fileForm.basicScore"
                @change="
                  val => {
                    scoreInputChange(fileForm, val)
                  }
                "
              >
                <template #prepend>
                  <el-icon :size="12">
                    <Plus />
                  </el-icon>
                </template>
              </el-input>
              <!--      减分        -->
              <el-input
                v-model="fileForm.scoreSelf"
                type="number"
                :max="fileForm.score * 1"
                v-else-if="fileForm.scoreMethod == '4'"
                @change="
                  val => {
                    scoreInputChange(fileForm, val)
                  }
                "
              >
                <template #prepend>
                  <el-icon :size="12"> 扣</el-icon>
                </template>
              </el-input>
              <el-input-number
                v-else
                :min="
                  fileForm.scoreMethod == '1'
                    ? fileForm.score == '减分项' ||
                      fileForm.score == '加/减分项'
                      ? -9999
                      : 0
                    : 0
                "
                :max="
                  fileForm.scoreMethod == '3'
                    ? fileForm.score - fileForm.basicScore
                    : fileForm.scoreMethod == '1'
                    ? fileForm.scope == '加分项'
                      ? 9999
                      : fileForm.score * 1
                    : fileForm.score * 1
                "
                v-model="fileForm.scoreSelf"
                :disabled="fileForm.scoreMethod == '2'"
                @input="
                  val => {
                    handleGradeBlur(fileForm, val)
                  }
                "
                @change="
                  val => {
                    handleGradeInput(fileForm, val)
                  }
                "
              ></el-input-number>
            </el-form-item>
          </div>
        </el-form>

        <template #footer>
          <!--          <el-button @click="handleFileDialogClose"-->
          <!--            >{{ props.type == 'self' ? '取消' : '关闭' }}-->
          <!--          </el-button>-->
          <el-button type="primary" @click="handleFileDialogSave">
            确认
          </el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup name="ScoreTable">
import { isNumberStr, setSpanObj } from '@/utils'
import { format, subMonths, subYears } from 'date-fns'
import useUserStore from '@/store/modules/user'
import {
  getAssessHistoryList,
  getAssessItemByPerson,
  getAssessItemIdsByPerson,
  getSelfAssessItem,
  updateAssessScoreByPerson,
  updateSelfAssessScore
} from '@/api/officeManage/appraisal'
import { getCurrentInstance } from 'vue'
import { getUser } from '@/api/system/user'
import { delFile, uploadFile } from '@/api/salesManage/contractManage'
import { getListByBizIdAndTableName } from '@/api/fileManage'
import { viewFile } from '@/utils/commo'

import useAppStore from '@/store/modules/app'
import { getAssessViewList } from '@/api/officeManage/performance'

const appStore = useAppStore()
const router = useRouter()
const userStore = useUserStore()
const { proxy } = getCurrentInstance()

const props = defineProps({
  type: {
    type: String,
    default: 'self'
  },
  userId: {
    type: String,
    default: ''
  },

  info: {
    type: Object,
    default: () => {}
  }
})

const data = reactive({
  tableData: [],
  spanObj: {
    firstLevel: { span: [] },
    secondLevel: { span: [] }
  },
  indexNum: {},
  appraiseeId: '', //用户id
  assessAtMonth: '', //考核月份
  assessAtYear: '', //考核年份
  isActive: 0, //当前选择人员
  userIds: [], //他评考核人员ids
  userInfo: {}, //被考核人用户信息
  fileList: [], // 上传文件列表
  selfFileList: [], //他评时自评上传文件显示
  dialogVisible: false, //上传文件弹窗
  fileForm: {
    scoreDescriptionSelf: ''
  },
  loading: false
})
const {
  tableData,
  spanObj,
  indexNum,
  appraiseeId,
  assessAtMonth,
  assessAtYear,
  isActive,
  userIds,
  userInfo,
  fileList,
  selfFileList,
  dialogVisible,
  fileForm,
  loading
} = toRefs(data)
const { scoring_method, indicator_unit } = proxy.useDict(
  'scoring_method',
  'indicator_unit'
)
const assessRemark = ref('')
const emits = defineEmits(['switchModule'])

/**
 * 获取前一次考评评分
 */
const getPreScore = async () => {
  let month = format(subMonths(new Date(), 2), 'MM')
  let params = {
    appraiseeId:
      props.type == 'self' ? appraiseeId.value : userIds.value[isActive.value],
    assessAtMonth: format(subMonths(new Date(), 2), 'MM'),
    assessAtYear:
      month == '12'
        ? format(subYears(new Date(), 1), 'yyyy')
        : format(new Date(), 'yyyy'),
    // format(subMonths(new Date(), 1), 'yyyy'),
    assessorId: props.type == 'self' ? '' : userStore.userInfo.userId,
    selfType: props.type
  }
  getAssessHistoryList(params).then(res => {
    if (res.data != null) {
      tableData.value.forEach(item => {
        let obj = res.data.find(t => t.confId == item.confId)
        if (obj) {
          if (props.type == 'self') {
            item.scoreSelf = obj.scoreSelf
            //   自评最终得分
            item.finalScoreSelf = obj.finalScoreSelf
          } else if (props.type == 'other') {
            item.scoreSelf = obj.score
            //   他评最终得分
            item.finalAssessScore = obj.finalScore
          }
        }
      })
    }
  })
}

/**
 * @description: 附件弹窗保存
 */
const handleFileDialogSave = () => {
  if (fileList.value.length > 0) {
    tableData.value.forEach(item => {
      if (item.scoreId == fileForm.value.scoreId) {
        // 自评
        if (props.type == 'self') {
          item.fileName = fileList.value.map(item => item.fileName)
        } else {
          // 他评
          item.fileName = fileList.value.map(item => item.fileName)
        }

        item.fileNum = fileList.value.length + ''
      }
    })
  }

  console.info('上传文件后表格tableData数据', tableData.value)
  dialogVisible.value = false
}

/**
 * @description：附件弹窗关闭
 * @param params
 * @returns {Promise<void>}
 */
const handleFileDialogClose = () => {
  fileList.value = []
  fileForm.value = {
    scoreDescriptionSelf: ''
  }
  dialogVisible.value = false
}

/**文件上传 限制条件**/
function beforeAvatarUpload(rawFile) {
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
}

// 上传附件
async function handleFileChange(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      fileList.value.push(res.data)
    }
  } catch (error) {
    console.log(error)
    proxy.$modal.msgError(error)
  }
}

// 删除文件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = fileList.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        fileList.value.splice(index, 1)
        tableData.value.forEach(item => {
          if (item.scoreId == fileForm.value.scoreId) {
            item.fileName = fileList.value.map(item => item.fileName)
          }
        })
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    console.log(error)
    proxy.$modal.msgError(error)
  }
}

/**
 * 上传指标附件弹窗
 */
const handleUploadFile = row => {
  // 自评
  if (props.type == 'self') {
    fileList.value = row.fileList
  } else {
    // 他评
    selfFileList.value = row.selfFileList
    fileList.value = row.fileList
  }
  fileForm.value = row
  dialogVisible.value = true
}

/**
 * @description: 录入情况下评分input框change方法
 */
const scoreInputChange = (row, val) => {
  if (!isNumberStr(val) && val != '') {
    proxy.$modal.msgError('请输入数字，最多保留两位小数')
    row.scoreSelf = null
    handleGradeInput(row, null)
  } else if (val == '') {
    handleGradeInput(row, null)
  } else {
    let inputVal = val * 1
    switch (row.score) {
      //加分项
      case '加分项':
        if (inputVal < 0) {
          proxy.$modal.msgError('请输入正数或0，最多保留两位小数')
          row.scoreSelf = null
          handleGradeInput(row, null)
        } else {
          handleGradeInput(row, val)
        }
        break
      //加减分项
      case '加/减分项':
        handleGradeInput(row, val)
        break
      //减分项
      case '减分项':
        if (inputVal > 0) {
          proxy.$modal.msgError('请输入负数或0，最多保留两位小数')
          row.scoreSelf = null
          handleGradeInput(row, null)
        } else {
          handleGradeInput(row, val)
        }
        break
      default:
        if (inputVal < 0) {
          proxy.$modal.msgError('请输入正数或0，最多保留两位小数')
          row.scoreSelf = null
          handleGradeInput(row, null)
        } else if (inputVal > row.score * 1) {
          row.scoreSelf = row.score
          handleGradeInput(row, row.score)
        } else {
          handleGradeInput(row, val)
        }
        break
    }
  }
}

const handleGradeBlur = (row, val) => {
  if (val === null) {
    props.type == 'self'
      ? (row.finalScoreSelf = '')
      : (row.finalAssessScore = '')

    return
  }
}

/**
 * @description: 评分输入框input方法
 */
const handleGradeInput = (row, val) => {
  console.info('val', val)
  console.info('props.value.type', props.type)

  if (val === null) {
    props.type == 'self'
      ? (row.finalScoreSelf = '')
      : (row.finalAssessScore = '')
    return
  }
  let inputVal = val * 1
  switch (row.scoreMethod) {
    //录入
    case '1':
      props.type == 'self'
        ? (row.finalScoreSelf = inputVal)
        : (row.finalAssessScore = inputVal)

      break
    // 完成率
    case '2':
      props.type == 'self'
        ? (row.finalScoreSelf = inputVal)
        : (row.finalAssessScore = inputVal)
      break
    //加分
    case '3':
      let scoreVal = row.basicScore + inputVal
      props.type == 'self'
        ? (row.finalScoreSelf = scoreVal)
        : (row.finalAssessScore = scoreVal)
      break
    //减分
    case '4':
      console.info('val', val)
      console.info('row.score', row.score)
      console.info('row.score - inputVal', row.score - inputVal)
      console.info('final_score_self', row.finalScoreSelf)

      let scoreValue = row.score - inputVal
      props.type == 'self'
        ? (row.finalScoreSelf = scoreValue)
        : (row.finalAssessScore = scoreValue)

      break

    default:
      break
  }
}

//计算评分
const scoreDescriptionSelfInput = (val, row) => {
  if (row.scoreMethod == '2') {
    //   计算百分比
    let percentage =
      Math.round(
        ((props.type == 'self'
          ? row.scoreDescriptionSelf * 1
          : row.assessDescription * 1) /
          row.targetValue) *
          10000
      ) / 100
    console.info('row.scoreStandardCode', row.scoreStandardCode)
    let rate = percentage * 0.01
    switch (row.scoreStandardCode) {
      case '1':
        if (percentage >= 60) {
          row.scoreSelf =
            rate * row.score > row.score ? row.score : rate * row.score
        } else {
          row.scoreSelf = 0
        }
        break
      case '2':
        if (percentage >= 60) {
          row.scoreSelf =
            rate * row.score > row.score ? row.score : rate * row.score
        } else if (percentage == 0) {
          row.scoreSelf = 0 - row.score
        } else {
          row.scoreSelf = 0
        }
        break
      case '3':
        row.scoreSelf =
          rate * row.score > row.score ? row.score : rate * row.score
        break
      case '4':
        if (percentage >= 60) {
          row.scoreSelf =
            rate * row.score > row.score ? row.score : rate * row.score
        } else if (percentage == 0) {
          row.scoreSelf = 0 - row.score
        } else {
          row.scoreSelf = 0
        }
        break
      case '5':
        if (percentage >= 60) {
          row.scoreSelf =
            rate * row.score > row.score * 1.2
              ? row.score * 1.2
              : rate * row.score
        } else {
          row.scoreSelf = 0
        }
        break
      case '6':
        if (percentage >= 60) {
          row.scoreSelf =
            rate * row.score > row.score * 1.3
              ? row.score * 1.3
              : rate * row.score
        } else {
          row.scoreSelf = 0
        }
        break
    }
    console.info(' row.scoreSelf', row.scoreSelf)
    row.scoreSelf = row.scoreSelf.toFixed(2)

    handleGradeInput(row, row.scoreSelf)
  }
}

/**
 * @description: 保存（他评）
 */
const handleSave = () => {
  let params = {
    //   被考核人id
    appraiseeId: userIds.value[isActive.value],
    //   考核人id
    assessorId: userStore.user.userId
  }
  params.updatePAssessScoreItemDtoList = tableData.value.map(item => {
    return {
      id: item.id,
      scoreDetailId: item.scoreDetailId,
      fileName: item.fileName,
      finalAssessScore: item.finalAssessScore,
      assessDescription: item.assessDescription,
      assessScore: item.scoreSelf
    }
  })
  //更新考绩效考评他评分数（按人员）
  updateAssessScoreByPerson(params).then(res => {
    proxy.$modal.msgSuccess(res.msg)
  })
}

/**
 * 切换人
 */
const handleSwitchPerson = type => {
  loading.value = true
  let params = {
    //   被考核人id
    appraiseeId: userIds.value[isActive.value],
    //   考核人id
    assessorId: userStore.user.userId
  }
  params.updatePAssessScoreItemDtoList = tableData.value.map(item => {
    return {
      id: item.id,
      scoreDetailId: item.scoreDetailId,
      fileName: item.fileName,
      finalAssessScore: item.finalAssessScore,
      assessDescription: item.assessDescription,
      assessScore: item.scoreSelf
    }
  })
  //更新考绩效考评他评分数（按人员）
  updateAssessScoreByPerson(params).then(res => {
    if (type == 'pre') {
      isActive.value = --isActive.value
    } else if (type == 'next') {
      isActive.value = ++isActive.value
    }
    console.info(' isActive.value ', isActive.value)
    console.info(' userIds.value ', userIds.value)
    getAssessItemByPersonApi(userIds.value[isActive.value])
  })
}

/**
 * @description: 提交
 */
const handleSubmit = () => {
  if (tableData.value.length == 0) {
    proxy.$modal.msgWarning('考评数据为空，无法提交！')
  }
  let params = {
    appraiseeId: appraiseeId.value
  }
  params.updateSelfAssessScoreItemDtoList = tableData.value.map(item => {
    return {
      scoreId: item.scoreId,
      fileName: item.fileName,
      remark: item.remark ? item.remark : '',
      id: item.id,
      finalScoreSelf: item.finalScoreSelf,
      scoreDescriptionSelf: item.scoreDescriptionSelf,
      scoreSelf: item.scoreSelf
    }
  })
  updateSelfAssessScore(params).then(res => {
    proxy.$modal.msgSuccess(res.msg)
    // routerBack()
    handleBack('list')
  })
}

/**
 * @description: 返回
 */
const handleBack = type => {
  emits('switchModule', 'evaluationList', props.type)
}

const routerBack = () => {
  router.back()
}
// 处理加法精度问题
const numAdd = (num1, num2) => {
  let maxLength, num1Length, num2Length
  // 如果参数无法被转换成数字类型则返回0
  if (isNaN(Number(num1)) || isNaN(Number(num2))) {
    return 0
  }
  try {
    num1Length = num1.toString().split('.')[1].length
  } catch (e) {
    num1Length = 0
  }
  try {
    num2Length = num2.toString().split('.')[1].length
  } catch (e) {
    num2Length = 0
  }
  maxLength = Math.pow(10, Math.max(num1Length, num2Length))
  //  将两位浮点数同时扩大n倍
  let num11 =
    num1.toString().split('.').join('') +
    new Array(num1Length > num2Length ? 0 : num2Length - num1Length)
      .fill('0')
      .join('')
  let num22 =
    num2.toString().split('.').join('') +
    new Array(num2Length > num1Length ? 0 : num1Length - num2Length)
      .fill('0')
      .join('')
  return (Number(num11) + Number(num22)) / maxLength
}

/**
 * 合计行
 */
const getSummaries = param => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 9) {
      sums[index] = '合计：'
      return
    } else if (index == 10) {
      if (props.type == 'self') {
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => Number.isNaN(value))) {
          sums[index] = `${values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!Number.isNaN(value)) {
              return numAdd(prev, curr) //prev + curr
            } else {
              return numAdd(prev, 0) //prev
            }
          }, 0)}`
        } else {
          sums[index] = '-'
        }
      } else {
        sums[index] = ''
      }
    } else if (index == 11) {
      if (props.type == 'other') {
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => Number.isNaN(value))) {
          sums[index] = `${values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!Number.isNaN(value)) {
              return numAdd(prev, curr) //prev + curr
            } else {
              return numAdd(prev, 0) //prev
            }
          }, 0)}`
        } else {
          sums[index] = '-'
        }
      } else {
        sums[index] = ''
      }
    } else {
      sums[index] = ''
    }
  })
  return sums
}

/**
 * @description: 合并单元格
 */
const spanMethod = ({ row, column, rowIndex, columnIndex }) => {
  for (let i = 0; i < tableData.value.length; i++) {
    const ele = tableData.value[i]

    if (spanObj.value[column.property]) {
      const _row = spanObj.value[column.property].span[rowIndex]
      const _col = _row > 0 ? 1 : 0
      return {
        rowspan: _row,
        colspan: _col
      }
    }
    // else if (column.type == 'index') {
    //   const _row = spanObj.value.firstLevel.span[rowIndex]
    //   const _col = _row > 0 ? 1 : 0
    //   return {
    //     rowspan: _row,
    //     colspan: _col
    //   }
    // }
    else {
      return {
        rowspan: 1,
        colspan: 1
      }
    }
  }
}

/**
 * @description: 自定义序号
 * @param index
 * @returns {*}
 */
const indexMethod = index => {
  return indexNum.value[index]
}

/**
 * 设置自定义序号
 */
const indexObj = key => {
  let num = 0
  spanObj.value[key].span.forEach((item, index) => {
    if (item != 0) {
      indexNum.value[index] = num += 1
    }
  })
}

/**
 * 获取用户绩效考核信息
 */
const getSelfAssessItemApi = async () => {
  let params = {
    appraiseeId: appraiseeId.value
  }
  await getSelfAssessItem(params).then(res => {
    tableData.value = res.data
    // setRemark(res.data)
    // 初始化合并行
    setSpanObj(spanObj.value, tableData.value)

    //
    indexObj('firstLevel')
  })
}
/**
 * 备注去重
 */
const setRemark = data => {
  const uniqueAssessRemark = {}
  const uniqueAssessRemarkArray = []

  data.forEach(obj => {
    const remark = obj.assessRemark
    if (!uniqueAssessRemark[remark]) {
      uniqueAssessRemark[remark] = true
      uniqueAssessRemarkArray.push(remark)
    }
  })
  console.info('uniqueAssessRemarkArray', uniqueAssessRemarkArray)

  assessRemark.value = uniqueAssessRemarkArray.join(' ')
}

/**
 * 获取绩效考核（按人员）id列表
 */
const getAssessItemIdsByPersonApi = () => {
  //   查询考核人下面的被考核人ids
  let params = {
    assessorId: appraiseeId.value
  }
  getAssessItemIdsByPerson(params).then(res => {
    console.info('res', res)
    if (res.data != null) {
      //   ids
      userIds.value = res.data
      if (Object.keys(props.info).length != 0) {
        console.info('props.info', props.info)
        isActive.value = res.data.findIndex(
          item => item == props.info.appraiseeId
        )
      }
      //默认第一个被考核人id
      getAssessItemByPersonApi(res.data[isActive.value])
    }
  })
}

/**
 * 获取绩效考核（按人员）信息
 */
const getAssessItemByPersonApi = id => {
  loading.value = true
  let params = {
    appraiseeId: id,
    assessorId: userStore.user.userId
  }
  getAssessItemByPerson(params)
    .then(res => {
      if (res.data != null) {
        let arr = JSON.parse(JSON.stringify(res.data))
        arr.forEach(item => {
          item.scoreSelf = item.assessScore
        })
        tableData.value = arr
        // setRemark(arr)
        // 初始化合并行
        setSpanObj(spanObj.value, tableData.value)
        //
        indexObj('firstLevel')
        loading.value = false
      }
    })
    .catch(err => {
      loading.value = false
    })
}

/**
 * @description: 初始化
 */
const init = async () => {
  appraiseeId.value = userStore.user.userId
  //     判断当前type是自评还是他评
  if (props.type == 'self') {
    // 自评
    // 获取当前用户的考核次数

    await getSelfAssessItemApi()
  } else {
    // 他评
    // 获取他评用户ids
    await getAssessItemIdsByPersonApi()
  }
}

// 展开菜单栏
onBeforeUnmount(() => {
  if (!appStore.sidebar.opened) {
    appStore.sidebar.opened = true
  }
})

init()
</script>

<style scoped lang="scss">
:deep(.el-table .el-table__row) {
  font-size: 12px !important;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number__decrease) {
  width: 23px !important;
}

:deep(.el-input-number__increase) {
  width: 23px !important;
}

.i-cil-paperclip:hover {
  cursor: pointer;
  color: #48a0f3 !important;
}

:deep(.el-input-number .el-input__wrapper) {
  padding-left: 35px;
  padding-right: 35px;
}

:deep(.el-table__footer-wrapper .cell) {
  color: red !important;
  font-weight: 600;
}

:deep(.el-input-group__prepend) {
  padding: 0 7px;
}
</style>
